package com.databasteknik.krustykookiez;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class Blocking extends JPanel implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4730061869075879344L;
	/**
	 * 
	 */
	private Database db;
	private JButton addButton;
	private JTextField txtfield;
	private DefaultTableModel tableModel;
	private String[] columnNames = {"Barcode", "Recipe", "Production date"};

	public Blocking(Database db) {
		this.db = db;
		setLayout(new BorderLayout());
		JPanel ep = new JPanel();
		JPanel wp = new JPanel();
		JPanel np = new JPanel();
		np.add(ep, BorderLayout.EAST);
		np.add(wp, BorderLayout.WEST);
		addButton = new JButton("Add");
		ep.add(addButton);
		wp.add(new JLabel("Barcode: "));
		txtfield = new JTextField(15);
		wp.add(txtfield);
		addButton.addActionListener(this);
		txtfield.setEditable(true);
		add(np, BorderLayout.NORTH);
		add(createBottomPanel(), BorderLayout.CENTER);
		
	}
	
	
	public JComponent createBottomPanel(){
		tableModel = new DefaultTableModel(columnNames, 0) {
			private static final long serialVersionUID = 1L;
			@Override
			public boolean isCellEditable(int row, int column){
				return false;
			}
		};
		JTable table = new JTable(tableModel);
		
		ArrayList<String[]> list = db.getBlocked();
		for(int i = 0; i < list.size(); i++) {
			tableModel.insertRow(tableModel.getRowCount(), new Object[]{list.get(i)[0], list.get(i)[1], list.get(i)[2]});
		}
		JScrollPane bottomPane = new JScrollPane(table);
		return bottomPane;
	}

	public void actionPerformed(ActionEvent e) {
		String palletID = txtfield.getText();
		for (int i = 0; i < palletID.length(); i++) {
			if (!isDigit(palletID.charAt(i))) {
				JOptionPane.showMessageDialog(this, "Illegal input");
				return;
			}
		}
		db.setBlockedPallet(palletID);
		if (db.getSuccessFlag()) {
			JOptionPane.showMessageDialog(this, "Pallet " + palletID
					+ " successfully added.");
			tableModel.setNumRows(0);
			ArrayList<String[]> list = db.getBlocked();
			for(int i = 0; i < list.size(); i++) {
				tableModel.insertRow(tableModel.getRowCount(), new Object[]{list.get(i)[0], list.get(i)[1], list.get(i)[2]});
			}
		}else{
			JOptionPane.showMessageDialog(this, "Something went wrong when trying to add " + palletID);
		}
	}

	public boolean isDigit(char c) {
		return Character.isDigit(c);

	}
}
